package slave;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class MasterChannel {
	private Socket socket;
	private DataOutputStream output;
	private BufferedReader input;
		
	public MasterChannel(Socket socket) throws IOException {
		if (socket == null) {
			throw new NullPointerException("socket");
		}
		this.socket = socket;
		this.output = new DataOutputStream(socket.getOutputStream());
		this.input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
	}
	
	DataOutputStream getOutput() {
		return this.output;
	}
	public MasterChannelCall awaitCall() throws IOException {
		String incoming = this.input.readLine();
		
		if (incoming == null || incoming.isEmpty()) {
			return null;
		}
		String[] elements = incoming.split("%");
		if (elements.length == 0) {
			return null;
		}
		
		String[] params = new String[elements.length - 1];
		for (int i = 1; i < elements.length; i++) {
			params[i-1] = elements[i];
		}
		
		return new MasterChannelCall(this, elements[0], params);
	}
	
	public static MasterChannel connect(String host, int port) throws UnknownHostException, IOException {
		Socket socket = new Socket(host, port);
		return new MasterChannel(socket);
	}
	

	@Override
	protected void finalize() throws Throwable {
		this.input.close();
		this.input = null;
		this.output.close();
		this.output = null;
		this.socket.close();
		this.socket = null;
 
		super.finalize();
	}
}
